//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package impl

import (
	"bytes"
	"strings"

	"atomgit.com/openlinksaas-org/search-proxy/core"
	"github.com/antchfx/htmlquery"
)

type NpmjsParser struct{}

func (parser *NpmjsParser) MatchUrl(url string) bool {
	return strings.HasPrefix(url, "https://www.npmjs.com/search")
}

func (parser *NpmjsParser) Parse(url string) ([]*core.SearchEntry, error) {
	body, err := GetPage(url)
	if err != nil {
		return nil, err
	}

	doc, err := htmlquery.Parse(bytes.NewBuffer(body))
	if err != nil {
		return nil, err
	}

	retList := []*core.SearchEntry{}
	linkElList := htmlquery.Find(doc, "//section//a")
	for _, linkEl := range linkElList {
		href := htmlquery.SelectAttr(linkEl, "href")
		if strings.HasPrefix(href, "/package/") {
			summary := ""
			if linkEl.Parent != nil && linkEl.Parent.Parent != nil {
				summary = htmlquery.InnerText(linkEl.Parent.Parent)
			}
			retList = append(retList, &core.SearchEntry{
				Title:   htmlquery.InnerText(linkEl),
				Url:     "https://www.npmjs.com" + htmlquery.SelectAttr(linkEl, "href"),
				Summary: summary,
			})
		}
	}
	return retList, nil
}
